package com.example.factory;

import com.example.exception.FactoryException;
import com.example.exception.ServiceException;
import com.example.service.IService;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2016/12/24.
 */
public class ServiceFactory {

    private static Map<String, IService> serviceCache = new HashMap<>();

    private ServiceFactory() {}


    /**
     * 通过工厂的方式获取服务实现类的实例,这里添加了微型缓存处理
     * @param service 服务实现类的全类名，exampleImpl.class.getName();
     * @return 服务实现类的实例
     */
    public static IService factory(String service) {

        if (serviceCache.size() > 10) {
            serviceCache.clear();
            // 后续可考虑使用LruCache最近最少使用算法
            System.out.println("service缓存已到达上限，清空缓存");
        }

        IService cache = serviceCache.get(service);

        if (cache == null) {
            try {
                Class<?> clazz = Class.forName(service);
                Object obj = clazz.newInstance();

                if (obj instanceof IService) {
                    serviceCache.put(service, (IService)obj);

                    return (IService) obj;
                } else {
                    throw new ServiceException("类型错误，"+ obj +"不是IService的服务实现类型");
                }
            } catch (ClassNotFoundException |
                    IllegalAccessException |
                    InstantiationException |
                    ServiceException e) {
                throw new FactoryException(ServiceFactory.class.getName() + "工厂出现异常", e);
            }
        }

        System.out.println("使用缓存中的service " + cache);
        return cache;
    }
}
